package com.berchen.test;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 */
public class ReadWriteLockDemo {

    private volatile Map<String,String> map=new HashMap<>();

    private ReentrantReadWriteLock rw=new ReentrantReadWriteLock();

    public void put(String key,String value){

        // 上写锁 只能一个线程访问
        rw.writeLock().lock();
        try {

            map.put(key,value);
        }catch (Exception e){

        }
        finally {

            rw.writeLock().unlock();
        }

    }
    public String get(String key){
        // 上读锁
        rw.readLock().lock();
        try{

            return map.get(key);
        }catch (Exception e){

            return "";
        }finally {
            rw.readLock().unlock();
        }
    }

    public static void main(String[] args) {

        ReadWriteLockDemo readWriteLockDemo = new ReadWriteLockDemo();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(()->{

                readWriteLockDemo.put("chen"+ finalI,"wan"+ finalI);
            }).start();
        }
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(()->{
                try {
                    Thread.sleep(1100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(readWriteLockDemo.get("chen" + finalI));
            }).start();
        }
    }
}
